package main

import (
	"fmt"
	"net"
)

/*
查字典服务端代码
*/
func main() {
	// 获取到服务端的socket对象
	sock, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("获取到服务端socket失败!", err)
	}
	// 初始化字典
	var dict = map[string]string{
		"rice":   "米饭",
		"hello":  "你好",
		"golang": "Go语言",
	}
	defer sock.Close()
	for {
		// 监听客户端的连接
		fmt.Println("等待客户端建立连接!")
		conn, _ := sock.Accept()
		fmt.Println("客户端建立连接成功!")
		conn.Write([]byte("欢迎来到米饭字典服务!\n"))
		for {
			// 接收客户端的英文单词
			var wordArr = make([]byte, 1024)
			n, err := conn.Read(wordArr)
			if err != nil {
				fmt.Println("接收客户端输入错误!", err)
			}
			var word = string(wordArr[:n])
			fmt.Println("接收到客户端输入:", word)
			// 退出逻辑
			if word == ":wq" {
				break
			}
			answer, exists := dict[word]
			if !exists {
				answer = "字典暂未收录该词汇!"
			}
			// 返回响应结果
			conn.Write([]byte(answer))
		}
		fmt.Println("客户端断开连接!")
		conn.Close()
	}
}
